# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import csv
import os

from itemadapter import ItemAdapter


class DoubanPipeline:
    def process_item(self, item, spider):
        # 判断是否存在download文件夹，如果没有则创建
        download_path = os.getcwd() + '/download/'  # 当前文件夹下的download文件夹
        if not os.path.exists(download_path):  # 判断文件夹或文件
            os.makedirs(download_path)

        msg_type = item.get("type")
        if msg_type == "info":
            # # 信息
            # {
            #     "type": "info",
            #     "img_src": img_src,
            #     "title": title,
            #     "rating_num": rating_num,
            #     "people_num": people_num
            # }
            # 如果是信息，就保存到csv文件
            with open(download_path + '豆瓣电影TOP250.csv', 'a') as f:
                # 创建一个csv的DictWriter对象，这样才能够将写入csv格式数据到这个文件
                f_csv = csv.DictWriter(f, ['title', 'img_src', 'rating_num', 'people_num'])
                # 写入多行行（当做数据）
                item.pop("type")  # 删除type 这个key-value
                f_csv.writerows([item])
                print("保存信息到CSV....ok")

        elif msg_type == "img":
            # 存储图片
            with open(download_path + item.get("img_name"), "wb") as f:
                f.write(item.get("img_bytes"))
                print("保存图片ok....")

        return item
